import logging
from contextlib import asynccontextmanager
from time import time

from app.core.config import settings
from app.core.database import mongodb
from app.routers.router import router
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.requests import Request
from fastapi.responses import JSONResponse

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用生命周期管理

    在应用启动时初始化数据库，在应用关闭时清理资源
    """
    # 启动时初始化数据库
    logger.info("🚀 正在启动应用...")
    await mongodb.initialize()
    logger.info("✅ 应用启动完成")

    yield

    # 关闭时的清理工作（如果需要）
    logger.info("👋 应用正在关闭...")


# Initialize FastAPI app with lifespan
app = FastAPI(
    title=settings.TITLE,
    description=settings.DESCRIPTION,
    version=settings.VERSION,
    root_path=settings.BASE_URL,
    lifespan=lifespan,
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS.split(","),
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(router, prefix=settings.API_V1_STR)


@app.get("/")
async def root():
    return {
        "title": settings.TITLE,
        "version": settings.VERSION,
        "description": settings.DESCRIPTION,
        "api_prefix": settings.API_V1_STR,
    }


@app.get("/health")
async def health_check():
    """健康检查端点"""
    return {"status": "ok", "timestamp": time()}


@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    logger.exception(f"未处理异常: {exc}")
    return JSONResponse(status_code=500, content={"detail": "服务器内部错误，请联系管理员"})
